#include "renderer.h"

Renderer::Renderer(SDL_Window* mWindow, SDL_Renderer* mRenderer)
{
	this->mWindow = mWindow;
	this->mRenderer = mRenderer;
}

Renderer::~Renderer()
{

}

void Renderer::RenderText(SDL_Rect rect, std::string text, Uint8 R, Uint8 G, Uint8 B, Uint8 A)
{
    font = TTF_OpenFont("./source/fonts/bitlight10.ttf", 16);
    if (font == nullptr) {
        std::cerr << "Failed to load font " << std::endl;
        return;
    }

    SDL_Color color = { R, G, B, A };
    SDL_Surface* surface = TTF_RenderText_Blended(font, text.c_str(), { R,G,B,A });
    SDL_Texture* texture = SDL_CreateTextureFromSurface(mRenderer, surface);
    SDL_FreeSurface(surface);

    SDL_RenderCopy(mRenderer, texture, NULL, &rect);

    TTF_CloseFont(font);
    SDL_DestroyTexture(texture);
}

//Render an image with a rotated degree
void Renderer::renderRotatedTexture(SDL_Texture* Texture, const int degree, const double porpotionX, const double porpotionY, const double porpotionSizeX, const double porpotionSizeY) const
{
    //Pre-render
    int windowWidth, windowHeight;
    SDL_GetWindowSize(mWindow, &windowWidth, &windowHeight);

    //Render the images
    int imageWidth, imageHeight;
    SDL_QueryTexture(Texture, NULL, NULL, &imageWidth, &imageHeight);
    int X = porpotionX * windowWidth, Y = porpotionY * windowHeight;
    int W = porpotionSizeX * windowWidth, H = porpotionSizeY * windowHeight;
    SDL_Rect destRect = { X, Y, W, H };

    SDL_RenderCopyEx(mRenderer, Texture, NULL, &destRect, degree, NULL, SDL_FLIP_NONE);
}

void Renderer::RenderTexture(SDL_Texture* Texture, const double porpotionX, const double porpotionY, const double porpotionSizeX, const double porpotionSizeY)
{
    //Pre-render
    int windowWidth, windowHeight;
    SDL_GetWindowSize(mWindow, &windowWidth, &windowHeight);

    //Render the images
    int imageWidth, imageHeight;
    SDL_QueryTexture(Texture, NULL, NULL, &imageWidth, &imageHeight);
    int X = porpotionX * windowWidth, Y = porpotionY * windowHeight;
    int W = porpotionSizeX * windowWidth, H = porpotionSizeY * windowHeight;
    SDL_Rect destRect = { X, Y, W, H };

    SDL_RenderCopy(mRenderer, Texture, NULL, &destRect );
}

SDL_Renderer* Renderer::getRenderer()
{
    return this->mRenderer;
}

SDL_Window* Renderer::getWindow()
{
    return this->mWindow;
}

void Renderer::RenderRect(SDL_Rect rect, Uint8 R, Uint8 G, Uint8 B, Uint8 A)
{
    SDL_SetRenderDrawBlendMode(mRenderer, SDL_BLENDMODE_BLEND);
    SDL_SetRenderDrawColor(mRenderer, R, G, B, A);
    SDL_RenderFillRect(mRenderer, &rect);
}